import { defineStore } from "pinia";
import { providerTheme } from "@/configs/ant.config";
import { LocalStorage } from "@webxue/common";
import { useSysConfig } from "@/configs/sys.config";
import { BaseApi } from "@/apis/base.api";

export const useConfigStore = defineStore("configStore", {
  state: () => ({
    // ant主题色
    providerTheme: {} as Record<string, any>,
    // 免鉴权配置
    publicConfigJson: LocalStorage.get(useSysConfig().localKey?.publicConfigJson) || {},
  }),
  getters: {},
  actions: {
    // 设置ant主题色
    setProviderTheme(theme: any = providerTheme) {
      this.providerTheme = theme;
    },
    // 设置免鉴权配置
    async setConfigJson(){
      const response = await BaseApi.sysConfig.getConfigJson();
      this.publicConfigJson = response.data;
      LocalStorage.set(useSysConfig().localKey?.publicConfigJson, this.publicConfigJson);
      // 如果存在iconfont图标则自动创建
      if(this.publicConfigJson.iconfontPath) {
        this.loadCSS(this.publicConfigJson.iconfontPath);
      }
    },
    // 移出免鉴权配置
    removeConfigJson(){
      this.publicConfigJson = {};
      LocalStorage.remove(useSysConfig().localKey?.publicConfigJson);
    },
    /**
     * 加载远程 CSS 文件
     * @param {string} url - CSS 文件的 URL
     */
    loadCSS(url:string) {
      const link = document.createElement("link");
      link.rel = "stylesheet";
      link.type = "text/css";
      link.href = url + "?_t=" + Date.now();
      document.head.appendChild(link);
    }
  }
});